/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bash.carrep.ui;

import com.bash.carrep.business.LoginBusiness;
import com.bash.carrep.business.exception.LoginExeption;
import com.bash.carrep.dao.enties.Login;
import com.bash.carrep.ui.util.LoginFieldFactory;
import com.vaadin.ui.Button;
import com.vaadin.ui.Window;
import com.vaadin.ui.themes.BaseTheme;
import java.util.Arrays;

/**
 *
 * @author bash
 */
public class LoginForm extends AbstractFrom {

    Login login;

    public LoginForm(CarrepApplication app) {
        super(app, Login.class);

        setFormFieldFactory(new LoginFieldFactory());
        login = (Login) pojo;

        setItemDataSource(bi);
        setVisibleLabels(Arrays.asList(new String[]{"username", "password"}));
        buildButtons();


    }

    @Override
    void buildButtons() {
        buttons.setSpacing(true);


        Button apply = new Button("Connection", new Button.ClickListener() {

            @Override
            public void buttonClick(Button.ClickEvent event) {
                submit();
            }
        });
        buttons.addComponent(apply);
        form.getLayout().addComponent(buttons);


        Button passwordRecovery = new Button("Mot de passe oublié?",
                new Button.ClickListener() {

                    @Override
                    public void buttonClick(Button.ClickEvent event) {
                        LoginForm.this.passwordRecovery();
                    }
                });

        passwordRecovery.setStyleName(BaseTheme.BUTTON_LINK);
        buttons.addComponent(passwordRecovery);
    }

    @Override
    void submit() {

//        if (!form.isValid()) {
//            return;
//        }
        form.commit();
        doLoginAction();
    }

    private void passwordRecovery() {
    }

    @Override
    void initDatasource() {
        form.setItemDataSource(bi, Arrays.asList(new String[]{"username", "password"}));
    }

    private void doLoginAction() {
        Login loginObject;
        try {

            loginObject = LoginBusiness.doLogin(login);

        } catch (LoginExeption ex) {
            showNotification("Erreur", Window.Notification.TYPE_ERROR_MESSAGE,
                    Window.Notification.POSITION_CENTERED_TOP, "<b>" + ex.getMessage() + "<b>");
            return;
        }

        if (loginObject != null) {
            app.setUser(loginObject);
            showNotification("Confirmation", Window.Notification.TYPE_HUMANIZED_MESSAGE,
                    Window.Notification.POSITION_CENTERED_TOP, "<b>Login Effectué avec succès pour<b> :" + login.getUsername() + " "
                    + "(pass:" + login.getPassword() + ")");

            app.enter();
        }


    }
}
